﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BattleAtms.Models;
using BattleAtms.Helpers;

namespace BattleAtms.Controllers
{
    public class HomeController : Controller
    {
        static Random _r = new Random();
        public IGame Game { get; set; }

        public HomeController()
        {
//            var ships = GameHelper.GenerateShips();

            Game = BattleAtms.Models.Game.GetInstance();

        }

        [HttpGet]
        public ActionResult Index()
        {
            int? userId = GetUserId();

            var model = new IndexModel();
            if (userId.HasValue)
            {
                model.GameState = Game.GetGameState(userId.Value);
                model.MyShips = Game.GetShips(userId.Value);
                int? opponentId = Game.GetOpponentId(userId.Value);
                if (opponentId.HasValue)
                {
                    model.OpponentShips = Game.GetShips(opponentId.Value);
                }
            }
            return View(model);
        }

        private int? GetUserId()
        {
            if (Request.Cookies["userId"] != null)
            {
                return int.Parse(Request.Cookies["userId"].Value);
            }
            return null;
        }

        [HttpPost]
        public ActionResult AjaxRegisterUser(string name)
        {
            int newUserId = Game.RegisterUser(name);
            return Json(new { id = newUserId });
        }

        [HttpPost]
        public ActionResult AjaxWaitForOpponent()
        {
            int userId = GetUserId().Value;
            var model = new WaitForOpponentModel();
            model.OpponentId = Game.GetOpponentId(userId);
            model.Users = Game.GetUsers(userId);
            return Json(model);
        }

        [HttpPost]
        public ActionResult AjaxDoTurn(int x, int y)
        {
            int userId = GetUserId().Value;
            int opponentId = Game.GetOpponentId(userId).Value;
            var state = Game.DoTurn(userId, x, y);
            //int n = _r.Next(4);
            //return Json(new { state = n });
            var opponentCells = Game.GetCells(opponentId);
            return Json(new { opponentCells = opponentCells });
        }

        [HttpPost]
        public ActionResult AjaxProceedGame()
        {
            int userId = GetUserId().Value;
            var state = Game.GetGameState(userId);
            var myCells = Game.GetCells(userId);
            return Json(new { state = state, myCells = myCells });
        }

        [HttpPost]
        public ActionResult AjaxStartGame(int opponentId)
        {
            int userId = GetUserId().Value;
            Game.StartGame(userId, opponentId);
            return Json(0);
        }
    }
}
